import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// const Login = () => import('@/views/login')
const LayoutIndex = () => import('@/views/layout')
const HomeIndex = () => import('@/views/layout/home')
const QuestionIndex = () => import('@/views/layout/question')
const UserIndex = () => import('@/views/layout/user')
const VideoIndex = () => import('@/views/layout/video')
const Search = () => import('@/views/search')
const Result = () => import('@/views/search/component/result')
const Article = () => import('@/views/article')
const Profile = () => import('@/views/layout/user/components/profile')
const Chat = () => import('@/views/layout/user/components/chat')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: () => import('@/views/login') },
    {
      path: '/',
      component: LayoutIndex,
      children: [
        { path: '', component: HomeIndex, meta: { iskeepAlive: true } },
        { path: '/question', component: QuestionIndex },
        { path: '/user', component: UserIndex },
        { path: '/video', component: VideoIndex }

      ]
    },
    { path: '/search', component: Search },
    { path: '/result', component: Result },
    // 动态路由匹配 携带参数
    { path: '/article/:id', component: Article },
    { path: '/userProfile', component: Profile },
    { path: '/userChat', component: Chat }
  ]

})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
const authLinks = ['/user', '/cart', '/userInfo']
router.beforeEach((to, from, next) => {
  // 访问页面是有权限的页面,就要先验证token
  if (authLinks.includes(to.path)) {
    // 有权限页面先判断是否有登录,验证token
    const token = store.state.user.tokenInfo.token
    // 有token直接放行
    if (token) {
      next()
    } else {
      // 没有token去登录页面
      // next('/login')
      next({
        path: '/login',
        query: {
          backTo: to.fullPath // fullPath 包含路由地址和参数 path只是路由地址
        }
      })
    }
  } else {
    // 放行
    next()
  }
})
export default router
